import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

export function request (config) {
  const instance = axios.create({
    baseURL: 'api',
    timeout: 5000
  })

  // 请求拦截
  instance.interceptors.request.use(config => {
    // 从本地存储中获取Token
    const token = sessionStorage.getItem('token')
    // 在请求头中添加Token
    if (token) {
      config.headers.token = token
    }
    return config
  }, err => {
    console.log('请求拦截err: ' + err)
  })
  // 2.2.响应拦截
  instance.interceptors.response.use(res => {
    const code = res.data.code
    if (code === 401) {
      return MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        location.href = '/'
      }).catch(() => {
        console.log(code)
      })
    } else if (code === 200) {
      return res.data
    } else {
      Message.error(res)
      return Promise.reject(res)
    }
  }, error => {
    console.log('err' + error)
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with Status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    return Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
  })

  // 3.发送真正的网络请求
  return instance(config)
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams (params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof (value) !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof (value[key]) !== 'undefined') {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}
